package com.atguigu.srb.core.service.impl;

import com.atguigu.srb.common.exception.BusinessException;
import com.atguigu.srb.core.enums.BorrowerStatusEnum;
import com.atguigu.srb.core.enums.IntegralEnum;
import com.atguigu.srb.core.mapper.BorrowerAttachMapper;
import com.atguigu.srb.core.mapper.BorrowerMapper;
import com.atguigu.srb.core.mapper.UserInfoMapper;
import com.atguigu.srb.core.pojo.entity.Borrower;
import com.atguigu.srb.core.pojo.entity.BorrowerAttach;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.pojo.entity.UserIntegral;
import com.atguigu.srb.core.pojo.vo.BorrowerApprovalVO;
import com.atguigu.srb.core.pojo.vo.BorrowerDetailVO;
import com.atguigu.srb.core.pojo.vo.BorrowerVO;
import com.atguigu.srb.core.service.BorrowerAttachService;
import com.atguigu.srb.core.service.BorrowerService;
import com.atguigu.srb.core.service.DictService;
import com.atguigu.srb.core.service.UserIntegralService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 借款人 服务实现类
 * </p>
 *
 * @author lwm
 * @since 2022-02-10
 */
@Service
public class BorrowerServiceImpl extends ServiceImpl<BorrowerMapper, Borrower> implements BorrowerService {
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private BorrowerAttachService borrowerAttachService;
    @Resource
    private DictService dictService;
    @Resource
    private BorrowerAttachMapper borrowerAttachMapper;
    @Resource
    private UserIntegralService userIntegralService;


    //提交借款人信息
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveBorrower(BorrowerVO borrowerVO, Long userId) {
        //根据userId查出会员信息
        UserInfo userInfo = userInfoMapper.selectById(userId);

        //保存借款人信息
        Borrower borrower = new Borrower();
        BeanUtils.copyProperties(borrowerVO,borrower);
        borrower.setUserId(userId);
        borrower.setName(userInfo.getName());
        borrower.setIdCard(userInfo.getIdCard());
        borrower.setMobile(userInfo.getMobile());
        borrower.setStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());
        baseMapper.insert(borrower);

        //保存附件  BorrowerAttach
        List<BorrowerAttach> borrowerAttachList = borrowerVO.getBorrowerAttachList();
        for (BorrowerAttach borrowerAttach : borrowerAttachList) {
            //设置借款编号
            borrowerAttach.setBorrowerId(borrower.getId());
        }
        //批量添加
        borrowerAttachService.saveBatch(borrowerAttachList);

        //更新用户的额度申请状态，更新为认证中
        userInfo.setBorrowAuthStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());
        userInfoMapper.updateById(userInfo);
    }

    //获取用户借款的审核状态
    @Override
    public Integer getBorrowerStatus(Long userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        return userInfo.getBorrowAuthStatus();
    }

    //获取借款人分页列表
    @Override
    public void listPage(Page<Borrower> page, String keyword) {
        LambdaQueryWrapper<Borrower> wrapper = null;
        if (StringUtils.hasText(keyword)){
            wrapper = new LambdaQueryWrapper<>();
            wrapper.like(Borrower::getIdCard,keyword)
                    .or().like(Borrower::getName,keyword)
                    .or().like(Borrower::getMobile,keyword);
        }
        baseMapper.selectPage(page,wrapper);
    }

    //获取借款人详细信息
    @Override
    public BorrowerDetailVO getBorrowerDetail(Long borrowerId) {
        //根据id获取借款人信息
        Borrower borrower = baseMapper.selectById(borrowerId);
        BorrowerDetailVO borrowerDetailVO = null;
        if (borrower != null){
            //填充基本借款人信息
            borrowerDetailVO = new BorrowerDetailVO();
            BeanUtils.copyProperties(borrower, borrowerDetailVO);
            //婚否
            borrowerDetailVO.setMarry(borrower.getMarry() ? "已婚":"未婚");
            //男女
            borrowerDetailVO.setSex(borrower.getSex()==1?"男":"女");
            //数据字典的文本值，根据dictValue找到文本值替换
            borrowerDetailVO.setEducation(dictService.getText("education",borrower.getEducation()));
            borrowerDetailVO.setIndustry(dictService.getText("industry", borrower.getIndustry()));
            borrowerDetailVO.setIncome(dictService.getText("income", borrower.getIncome()));
            borrowerDetailVO.setReturnSource(dictService.getText("returnSource", borrower.getReturnSource()));
            borrowerDetailVO.setContactsRelation(dictService.getText("relation", borrower.getContactsRelation()));
            //审批状态
            borrowerDetailVO.setStatus(BorrowerStatusEnum.getMsgByStatus(borrower.getStatus()));

            //附件列表 根据借款人Id查询附件集合
            borrowerDetailVO.setBorrowerAttachVOList(borrowerAttachMapper.selectVOByBorrowerId(borrowerId));
        }

        return borrowerDetailVO;
    }

    //借款额度审批
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void approval(BorrowerApprovalVO borrowerApprovalVO) {
        //获取borrower
        Borrower borrower = baseMapper.selectById(borrowerApprovalVO.getBorrowerId());
        if (borrower == null){
            throw new BusinessException("borrower不存在");
        }
        //获取用户信息
        Long userId = borrower.getUserId();
        UserInfo userInfo = userInfoMapper.selectById(userId);
        if (userInfo == null){
            throw new BusinessException("用户不存在");
        }
        //获取当前认证状态，进行比较
        Integer authStatus = borrowerApprovalVO.getStatus();
        Integer failStatus = BorrowerStatusEnum.AUTH_FAIL.getStatus();
        //认证失败的情况，更新用户表和借款人表的审批失败状态
        if (authStatus == failStatus.intValue()){
            userInfo.setBorrowAuthStatus(failStatus);
            borrower.setStatus(failStatus);
        }else {
            //新增积分记录
            //1、基础积分
            Integer totalIntegral = borrowerApprovalVO.getInfoIntegral();
            UserIntegral userIntegral = new UserIntegral();
            userIntegral.setUserId(userId);
            userIntegral.setIntegral(totalIntegral);
            userIntegral.setContent(IntegralEnum.BORROWER_INFO.getMsg());
            //创建集合来批量添加记录
            List<UserIntegral> userIntegralList = new ArrayList<>();
            userIntegralList.add(userIntegral);

            // 2、身份证
            if (borrowerApprovalVO.getIsIdCardOk()) {
                userIntegral = insertIntegral(IntegralEnum.BORROWER_IDCARD, userId);
                userIntegralList.add(userIntegral);
                totalIntegral += userIntegral.getIntegral();
            }
            //3、房产
            if (borrowerApprovalVO.getIsHouseOk()) {
                userIntegral = insertIntegral(IntegralEnum.BORROWER_HOUSE, userId);
                userIntegralList.add(userIntegral);
                totalIntegral += userIntegral.getIntegral();
            }
            //4、车
            if (borrowerApprovalVO.getIsCarOk()) {
                userIntegral = insertIntegral(IntegralEnum.BORROWER_CAR, userId);
                userIntegralList.add(userIntegral);
                totalIntegral += userIntegral.getIntegral();
            }
            //批量添加UserIntegral记录
            userIntegralService.saveBatch(userIntegralList);

            //设置borrower审核状态  用户新的总积分、审核状态
            borrower.setStatus(authStatus);
            userInfo.setIntegral(totalIntegral);
            userInfo.setBorrowAuthStatus(authStatus);
        }

        //更新borrower记录和userInfo记录
        baseMapper.updateById(borrower);
        userInfoMapper.updateById(userInfo);
    }

    //创建UserIntegral
    private UserIntegral insertIntegral(IntegralEnum integralEnum, Long userId) {
        UserIntegral userIntegral = new UserIntegral();
        userIntegral.setUserId(userId);
        userIntegral.setIntegral(integralEnum.getIntegral());
        userIntegral.setContent(integralEnum.getMsg());
        return userIntegral;
    }
}
